package com.xy.frame;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

import com.google.common.collect.Maps;

/**
 * Created by admin on 2014/3/27.
 */
public class WEBApp {

	private static Logger logger = LoggerFactory.getLogger(WEBApp.class);

	public static String APP_PATH = "/";

	public static ApplicationContext SPRING_CONTEXT = null;

	private static WEBApp SINGLETON = new WEBApp();

	private static Map<String, String> pros = new HashMap<String, String>();

	private static Map<String, Object> __CODE_ = Maps.newHashMap();

	public static void addCODE(List<Map<String, Object>> list) {
		// 清空当前类型
		__CODE_.clear();
		for (Map<String, Object> m : list) {
			__CODE_.put(m.get("F_TYPE_CODE") + "." + m.get("F_VALUE_CODE"),
					m.get("F_VALUE").toString());
		}
	}

	/**
	 * @param type
	 * @param code
	 * @return
	 */
	public static Object getCODE(String type, String code) {
		return __CODE_.get(type + "." + code);
	}
	/**
	 * @param type
	 * @param code
	 * @return
	 */
	public static void  setCODE(String type, String code,Object value) {
		  __CODE_.put(type + "." + code,value);
	}
	public static Map<String, String> getPros() {
		return pros;
	}

	public static void addPros(Map<String, String> input) {
		WEBApp.pros.putAll(input);
	}

	public static void setPros(Map<String, String> pros) {
		WEBApp.pros = pros;
	}

	private WEBApp() {
	}

	public static void initWEBApp(Properties properties) {
		if (SINGLETON == null) {
			SINGLETON = new WEBApp();
		}
		try {
			WEBApp.getPros().clear();
			Enumeration<?> en = properties.propertyNames();
			while (en.hasMoreElements()) {
				String strKey = en.nextElement().toString();
				WEBApp.getPros().put(strKey, properties.getProperty(strKey));
			}
		} catch (Exception e) {
			logger.error("加载系统配置文件出现异常!" + e.getMessage(), e);
			throw new RuntimeException("加载系统配置文件出现异常!" + e.getMessage(), e);
		}
	}

	/**
	 * 获取配置文件中的配置信息
	 * 
	 * 需要在 ams-config.xml 中配置 <bean id="WEBApp"
	 * 
	 * @param key
	 *            配置文件中的key
	 * @return
	 */
	public static String getValue(String key) {
		return pros.get(key);
	}

	public static HttpSession getSession(HttpServletRequest request) {
		HttpSession session = request.getSession();
		return session;
	}
}
